
window.CKEditorParams={
	
	odoc_xuhao1 : -1,
	odoc_xuhao2 : -1,
	odoc_xuhao3 : -1,
	odoc_xuhao4 : -1,
	
	attachment : -1,
	numData : {
		odoc_xuhao1:["一、","二、","三、","四、","五、","六、","七、","八、","九、"],
		odoc_xuhao2:["（一）","（二）","（三）","（四）","（五）","（六）","（七）","（八）","（九）"],
		odoc_xuhao3:["1.","2.","3.","4.","5.","6.","7.","8.","9.",],
		odoc_xuhao4:["（1）","（2）","（3）","（4）","（5）","（6）","（7）","（8）","（9）",],
	},	
	revisionStatus:false,//修订状态	
	endorseId:0,//批注序号 批注计数
	showPostil:true,//是否显示批注	
	insertId:0,//插入数据的id
	deleteId:0,//删除数据的id
	selectDelete:false,//是否是选择文字删除
	selectText:"",//选择的文本
	tempStr1:"",//获取焦点之前的文本
	//tempStr2:"",//获取焦点之后的文本
	start:0,//勾选的文字 所在节点的起始字符位置
	//end:0, //勾选的文字 所在节点的结束字符位置
	node:{},//勾选文字的节点
	author : "罗燕",//用户信息
	keyDownContinue :false, //是否值一直按着删除键
	deleteContinueCount:0,	//单条删除的文字计数
	insertContinueCount: 0,	//单条插入信息的文字的计数
	reviseCount:0, //修订计数
	reviseType : "insert",
	hoverDom:"",

}
var iframeWindow =""
var iframeDocument = "";


CKEditorParams.editorObject=CKEDITOR.replace( 'editor1',{   
	language : 'zh-cn',  
	extraPlugins: 'timestamp,pagebreak',
	on: {
	  pluginsLoaded: function() {
	    var editor = this,
	    config = editor.config;
	    
	    editor.ui.addRichCombo( 'my-combo', {
	        label: '序号',
	        title: '序号',
	        toolbar: 'clipboard,0',
	
	        panel: {               
	            css: [ CKEDITOR.skin.getPath( 'editor' ) ].concat( config.contentsCss ),
	            multiSelect: false,
	            attributes: { 'aria-label': 'My Dropdown Title' },
	        },
	
	        init: function() {    
	            this.add( '一，二，三', '一，二，三' );
	            this.add( '（一），（二），（三）', '（一），（二），（三）');                    
	            this.add( '1，2，3', '1，2，3');
	            this.add( '（1），（2），（3）', '（1），（2），（3）');                    
	        },
	
	        onClick: function(value){
	        	setNumber(value);
	        }
	    });
    
	    editor.ui.addRichCombo( 'attachment', {
	        label: '版式',
	        title: '版式',
	        toolbar: 'clipboard,0',
	        panel: {               
	            css: [ CKEDITOR.skin.getPath( 'editor' ) ].concat( config.contentsCss ),
	            multiSelect: false,
	            attributes: { 'aria-label': 'plate' },
	        },
	        init: function() {    
	          this.add( '附件', '附件' );
	          this.add( '附件(多个)', '附件(多个)' );
	          this.add('附注','附注')
	        },
	        onClick: function(value){
	        	insertAttachment(value);
	        }
	    });      
  	}
  }
});

var odocNumber = new CKEDITOR.style( { element: 'p', attributes: { 'class': 'odoc_wenhao' }} );
CKEditorParams.editorObject.addCommand( 'odocNumber', new CKEDITOR.styleCommand( odocNumber ) );

var docTitle = new CKEDITOR.style( { element: 'p', attributes: { 'class': 'odoc_zhubiaoti' }} );
CKEditorParams.editorObject.addCommand( 'docTitle', new CKEDITOR.styleCommand( docTitle ) );

var fubiaoti = new CKEDITOR.style( { element: 'p', attributes: { 'class': 'odoc_fubiaoti' }} );
CKEditorParams.editorObject.addCommand( 'fubiaoti', new CKEDITOR.styleCommand( fubiaoti ) );

var zhusong  = new CKEDITOR.style( { element: 'p', attributes: { 'class': 'odoc_zhusong' }} );
CKEditorParams.editorObject.addCommand( 'zhusong', new CKEDITOR.styleCommand( zhusong ) );

var zhengwen = new CKEDITOR.style( { element: 'p', attributes: { 'class': 'odoc_zhengwen' }} );
CKEditorParams.editorObject.addCommand( 'zhengwen', new CKEDITOR.styleCommand( zhengwen ) );

var shuming = new CKEDITOR.style( {element: 'p', attributes: { 'class': ' odoc_shuming1' }} );
CKEditorParams.editorObject.addCommand( 'shuming', new CKEDITOR.styleCommand( shuming ) );

var shuming = new CKEDITOR.style( {element: 'p', attributes: { 'class': ' odoc_shuming1' }} );
CKEditorParams.editorObject.addCommand( 'shuming', new CKEDITOR.styleCommand( shuming ) );

var fuzhu = new CKEDITOR.style( {element: 'p', attributes: { 'class': ' odoc_fuzhu' }} );
CKEditorParams.editorObject.addCommand( 'fuzhu', new CKEDITOR.styleCommand( fuzhu ) );

var qianshuriqi = new CKEDITOR.style( { element: 'p', attributes: { 'class': 'odoc_qianshuriqi1' }} );
CKEditorParams.editorObject.addCommand( 'qianshuriqi', new CKEDITOR.styleCommand( qianshuriqi ) );

var ck = {
  updateAll: function () {
    for (instance in CKEDITOR.instances) {
      CKEDITOR.instances["editor1"].updateElement();
    }
  },
  resetAll: function () {
    for (instance in CKEDITOR.instances) {
      CKEDITOR.instances["editor1"].setData("");
    }
  },
  update: function () {
    CKEDITOR.instances["editor1"].updateElement();
  },
  reset: function () {
    CKEDITOR.instances[id].setData("");
  },
  set: function ( content) {
    CKEDITOR.instances["editor1"].setData(content,function(){
		ready(true)
	});
  },
  get: function() {
    return CKEDITOR.instances["editor1"].getData();
  },
  insert: function ( content) {
    CKEDITOR.instances["editor1"].insertHtml(content);
  }
};
	
//change事件
CKEditorParams.editorObject.on( 'change', function(event) {

});

CKEditorParams.editorObject.on( 'setData', function(event) {
	
});

								
//keydown事件
CKEditorParams.editorObject.on("key", function(event){
	var e = event.data.domEvent.$;
	
	console.log(e.keyCode)
	if(e.keyCode == 8 || e.keyCode == 1){
		// if(CKEditorParams.revisionStatus && !jQuery("#cke_42").hasClass("cke_button_on"))
		// CKEDITOR.tools.callFunction(79);
		
		// if(!CKEditorParams.revisionStatus && jQuery("#cke_42").hasClass("cke_button_on"))
		// CKEDITOR.tools.callFunction(79);
	}else{
		// if(!jQuery("#cke_42").hasClass("cke_button_on"))
		// CKEDITOR.tools.callFunction(79);
		return;
	}
	console.log(e.keyCode)

	if(e.keyCode == 17 ){
		return 
	}
	if(CKEditorParams.revisionStatus){
		
		if(CKEditorParams.selectDelete){
			if(e.keyCode != 8){
				event.cancel();
				return ;
			}
		}

		if(e.keyCode == 8){

			//clearInsTag();
			if(event.editor.getSelection().getStartElement() && event.editor.getSelection().getStartElement().getAttribute("class") == "odoc_insertTag"){
				return;
			}else{
				if(CKEditorParams.deleteContinueCount == 0){
					if(iframeWindow.getSelection().extentNode && iframeWindow.getSelection().extentNode.parentElement){
						if(iframeWindow.getSelection().extentNode.parentElement.tagName != "BODY"){
							CKEditorParams.node = iframeWindow.getSelection().extentNode.parentElement;
						}else{
							CKEditorParams.node = iframeWindow.getSelection().extentNode;
						}
					}
				}else{
					CKEditorParams.node = iframeWindow.getSelection().baseNode.parentNode;
				}
				
				console.log("key",CKEditorParams.node)
			
				CKEditorParams.deleteContinueCount += 1;
				CKEditorParams.deleteId += 1
				
				if(event.editor.getSelection().getSelectedText().length > 0){
					deleteSelected(event)
					event.cancel();
				}else{

					deleteOne(event);
					
				}
			}
			
		}else{
			// if(iframeWindow.getSelection().extentNode && iframeWindow.getSelection().extentNode.parentElement){
			// 	if(iframeWindow.getSelection().extentNode.parentElement.tagName != "BODY"){
			// 		CKEditorParams.node = iframeWindow.getSelection().extentNode.parentElement;
			// 	}else{
			// 		CKEditorParams.node = iframeWindow.getSelection().extentNode;
			// 	}
			// }
			
			// if(CKEditorParams.node.className == "odoc_insertTag" || CKEditorParams.node.className == "odoc_insertTagInline"){
			// 	CKEditorParams.node.className = "odoc_insertTagInline";
			// }else{
			// 	insertText()
			// }
			
			
			// CKEditorParams.tempStr1= ""
			// CKEditorParams.tempStr2 = ""
			// var ctrlKey = e.ctrlKey || e.metaKey;
			
			// if(ctrlKey && keyCode == 37) {// 左
			// 	event.cancel();
			// }
			// if(ctrlKey && keyCode == 38) {// 上
			// 	event.cancel();
			// }
			// if(ctrlKey && keyCode == 39) {// 右
			// 	event.cancel();
			// }
			// if(ctrlKey && keyCode == 40) {// 下
			// 	event.cancel();
			// }
		}
	// }else{
	// 	var keyCode = e.keyCode || e.which || e.charCode;
	// 	if(keyCode == 8){
	// 		deleteSequence();
	// 	}
	// 	preventKey(e,keyCode)
	}
});

//拒绝修订
function rejectChange(dom){
	if(!CKEditorParams.revisionStatus){
		return ;
	}
	var insertTagItem = iframeDocument.getElementsByClassName("odoc_insertTagInline"); 
	for(var i = 0 ; i < insertTagItem.length;i++){
		insertTagItem[i].remove();
		i--;
	}
	
	dom.className="disabled";
}

//拒绝修订可以点击
function rejectChangeCanClick(){
	document.getElementById("rejectChange").setAttribute("class","");
}

//拒绝修订不可以点击
function rejectChangeCannotClick(){
	document.getElementById("rejectChange").setAttribute("class","disabled");
}


//清除没有内容的ins标签
function clearInsTag(){
	var insertTagItem = iframeDocument.getElementsByClassName("odoc_insertTag");
	for(var i = 0 ; i < insertTagItem.length;i++){
		if(insertTagItem[i].innerText == ""){
			insertTagItem[i].remove();
			i--;
		}
	}
}

//清除才生成的ins标签
function clearLastIns(){
	var insertTagItem = iframeDocument.getElementById("insertTag"+CKEditorParams.insertId);
	if(insertTagItem){
		insertTagItem.remove();
	}
}

//设置序号
function setNumber(value){
	var numData = CKEditorParams.numData;
	var className="";  		
	if(value == '1'){
		className = "odoc_xuhao1";
		CKEditorParams.odoc_xuhao1 += 1;
		CKEditorParams.odoc_xuhao2 = -1;
	}else if(value == '2'){
		className = "odoc_xuhao2";
		CKEditorParams.odoc_xuhao2 += 1;
		CKEditorParams.odoc_xuhao3 = -1;
		CKEditorParams.odoc_xuhao4 = -1;
	}else if(value == '3'){
		className = "odoc_xuhao3";
		CKEditorParams.odoc_xuhao3 += 1;
		CKEditorParams.odoc_xuhao4 = -1;
	}else if(value == '4'){
		CKEditorParams.odoc_xuhao4 += 1;
		className = "odoc_xuhao4";
	}
	if(CKEditorParams[className] > 9 ){
		var index = parseInt(CKEditorParams[className].toString().split("")[1])+1 || 0;
	}
	var element = CKEDITOR.dom.element.createFromHtml( '<p class="'+className+'">'+numData[className][CKEditorParams[className]]+'</p>' );
	CKEditorParams.editorObject.insertElement(element);
}
		 

//插入附件
function insertAttachment(value){
	if(CKEditorParams.attachment > 8){
		CKEditorParams.attachment
	}
	//单个附件
	if(value == "11"){
		var element = CKEDITOR.dom.element.createFromHtml( '<p class="odoc_fujian1" >附件：</p>' );
		CKEditorParams.editorObject.insertElement(element);
		//多个附件
	}else if(value == "12"){
		CKEditorParams.attachment += 1 ;
		var element = {} ;
		var length = iframeDocument.getElementsByClassName("odoc_fujian2").length;
		if(length == 0){
			element = CKEDITOR.dom.element.createFromHtml( '<p class="odoc_fujian2" >附件：'+CKEditorParams.numData["odoc_xuhao3"][CKEditorParams.attachment]+'</p>' );
		}else{
			element = CKEDITOR.dom.element.createFromHtml( '<p class="odoc_fujian3" >'+CKEditorParams.numData["odoc_xuhao3"][CKEditorParams.attachment]+'</p>' );
		}
		CKEditorParams.editorObject.insertElement(element);
		//附注
	}else if(value == "13"){
		var element = CKEDITOR.dom.element.createFromHtml( '<p class="odoc_fuzhu" >附注：</p>' );
		CKEditorParams.editorObject.insertElement(element);
	}
}

//修订
function revision(e){
	CKEditorParams.revisionStatus = !CKEditorParams.revisionStatus;
	var revise = document.getElementsByClassName("revise")[0]
	if(CKEditorParams.revisionStatus){

		// e.innerText ="修订中";
		// e.className="isRevision"
		// rejectChangeCanClick();
		revise.style.display="block";
	}else{
		// e.innerText ="修订";
		// e.className="noRevision"
		// rejectChangeCannotClick()
		revise.style.display="none";
	}
	
}
//打开或者选择文件以后

CKEditorParams.editorObject.on('elementsPathUpdate', function (e) { 	
	jQuery('.cke_wysiwyg_frame')[0].contentWindow.document.onclick = function(event){
		console.log('document.onclick',event)
		console.log('CKEditorParams.editorObject.getSelection().getSelectedText()',CKEditorParams.editorObject.getSelection().getSelectedText())
		if(CKEditorParams.editorObject.getSelection().getSelectedText() == ""){

		console.log('CKEditorParams.revisionStatus',CKEditorParams.revisionStatus);
		console.log('!jQuery("#cke_42")',jQuery("#cke_42").attr("class"));
			if(CKEditorParams.revisionStatus && !jQuery("#cke_42").hasClass("cke_button_on"))
			CKEDITOR.tools.callFunction(79);
			
			 if(!CKEditorParams.revisionStatus && jQuery("#cke_42").hasClass("cke_button_on"))
			 CKEDITOR.tools.callFunction(79);
		}
	}
});
//初始化函数
CKEDITOR.on('instanceReady', function (e) { 	
	CKEditorParams.author = JSON.parse (localStorage.getItem("theme-account")).username;
	document.getElementById("author").innerText = CKEditorParams.author;
	ready()
})

//初始化函数

function ready(bool){
	CKEditorParams.editorObject.focus();
		iframeDocument = document.getElementsByClassName('cke_wysiwyg_frame')[0].contentDocument;
		iframeWindow = document.getElementsByClassName('cke_wysiwyg_frame')[0].contentWindow;
	var iframeBody = iframeDocument.getElementsByTagName("body")[0];
	bool && getReviseItem() ;
	bool && getPositlItem() ;
	// iframeBody.addEventListener("click",bodyClick,false);
	iframeBody.onmousedown = function (){ 
		// console.log("------------onmousedown");
		// if(CKEditorParams.revisionStatus && !jQuery("#cke_42").hasClass("cke_button_on"))
		// CKEDITOR.tools.callFunction(79);
		
		// if(!CKEditorParams.revisionStatus && jQuery("#cke_42").hasClass("cke_button_on"))
		// CKEDITOR.tools.callFunction(79);
		return clearInsTag();
	}	
	iframeBody.onmouseup =  function (){ return bindSelection();}
	iframeBody.onkeyup = function (){ return deleteInsFrist();};
	iframeBody.onmouseover =function (e){ return showInfo(e);} 
	iframeBody.onclick = function(e){
		if(e.target.className != "odoc_insertTag" && e.target.className != "odoc_postilWord" 
			&& e.target.className != "odoc_postilWord1" && CKEditorParams.revisionStatus 
			&& CKEditorParams.selectText==""){
			clearInsTag();
		}
	}
	iframeBody.onkeyup = function(){
		CKEditorParams.keyDownContinue = false;
	}
}

//勾选文字事件
function bindSelection(e){
	
	if(CKEditorParams.revisionStatus){
		addRevise()
		clearInsTag();
	}
	
	CKEditorParams.insertContinueCount = 0
	CKEditorParams.deleteContinueCount = 0;
	
	var getSelected = iframeWindow.getSelection;
	CKEditorParams.selectText =  getSelected ? getSelected().toString():iframeDocument.selection.createRange().text;
//	CKEditorParams.node =	CKEditorParams.editorObject.getSelection().getRanges()[0].startContainer
		
  CKEditorParams.node= iframeWindow.getSelection().extentNode && iframeWindow.getSelection().extentNode.parentElement || null;
// CKEditorParams.node.innerHTML = CKEditorParams.node.innerHTML
  console.log("CKEditorParams.node",CKEditorParams.node)
	CKEditorParams.start = getSelected().focusOffset;
	CKEditorParams.end = getSelected().anchorOffset;

	
	try{

		CKEditorParams.tempStr1 = CKEditorParams.editorObject.getSelection().getCommonAncestor().$.wholeText.replace(/\u200B/g,'').substring(0,CKEditorParams.end); 
		console.log("CKEditorParams.tempStr1",CKEditorParams.tempStr1)
		CKEditorParams.tempStr2 = CKEditorParams.node.innerText.substring(CKEditorParams.start,CKEditorParams.node.innerText.length)
		if(CKEditorParams.selectText != ""){
			CKEditorParams.selectDelete = true;
			CKEditorParams.startIndex = CKEditorParams.node.innerText.indexOf(CKEditorParams.selectText);
		// creatPostilCanClick()
		}else{
			CKEditorParams.selectDelete = false;
			CKEditorParams.startIndex = CKEditorParams.start;
		// creatPostilCannotClick()
			
		}
		console.log("CKEditorParams.startIndex",CKEditorParams.startIndex)
	}catch(e){

	}
	
}

CKEditorParams.editorObject.on( 'blur', function(e) {

  CKEditorParams.deleteContinueCount = 0;
  
});

function deleteInsFrist(){
	var insDom = iframeDocument.getElementById("insertTag"+insertId);
	if(CKEditorParams.deleteContinueCount == 1 && insDom.innerText.length>1){
		insDom.innerText = insDom.innerText.slice(0,-1)
	}
}

//点击新建批注
function creatPostil(){
	if(CKEditorParams.selectText ==""){
		document.getElementsByClassName("ant-modal-content")[0].style.display = "block";
		return;
	}
	if(document.getElementsByClassName("creatPostil")[0].style.display =="block"){
		return;
	}
	showPostilList(false);
	CKEditorParams.endorseId += 1;
	var html = "<span class='odoc_postilWord' id='postilWord"+CKEditorParams.endorseId+"'>"+CKEditorParams.selectText+"</span>"; 
	html = "<span class='tempStr1'>"+CKEditorParams.tempStr1+"</span>" +html + "<span class='tempStr'>"+CKEditorParams.tempStr2+"</span>";
	CKEditorParams.node.innerHTML = html
	//CKEditorParams.editorObject.insertHtml(html);
	document.getElementsByClassName("creatPostil")[0].style.display="block";
	document.getElementById("canEdit").focus();
}

//批注方法
function postil(){
	var textarea = document.getElementById("canEdit");
	var insertHtmlString='<div class="headPortrait"><span class="odoc_author">'+CKEditorParams.author+'</span></div><div class="postilContent"><div class="postilTime">'+getPostilDate()+'</div><div class="postilText">'+textarea.value+'</div></div>'	;
	var postilItem = document.createElement("div");
	postilItem.setAttribute("class","postilItem");
	postilItem.setAttribute("id","postilItem"+CKEditorParams.endorseId);		
	postilItem.innerHTML = insertHtmlString;

	var nowTime = getDate()
	var postilWord = iframeDocument.getElementById("postilWord"+CKEditorParams.endorseId);	
	postilWord.setAttribute("pizhushijian",nowTime);
	postilWord.setAttribute("pizhuren",CKEditorParams.author);
	postilWord.setAttribute("pizhuneirong",textarea.value);	
	document.getElementById("postilBox").appendChild(postilItem)

	document.getElementById("postilNumber").innerText = CKEditorParams.endorseId + "处批注"

	creatPostilHide();
	noSelectText()
	// changePostilStatus()
}

//隐藏创建批注
function creatPostilHide(){
	document.getElementsByClassName("creatPostil")[0].style.display="none";
	document.getElementById("canEdit").value = "";
}

//获取最后后一个字符
function getLastChar(string){
	return string.substr(string.length-1,string.length);
}

//除去最后一个字符
function deleteLastChar(string){
	return string.substr(0,string.length-1);
}

//新建批注可以点击
function creatPostilCanClick(){
	document.getElementById("creatPostil").setAttribute("class","");
}

//新建批注不能点击
function creatPostilCannotClick(){
	document.getElementById("creatPostil").setAttribute("class","disabled");
}

//没有选择的文字清空
function noSelectText(){
	CKEditorParams.selectText = ""; 
	// creatPostilCannotClick()
}

//取消新建批注
function closeCreatPostil(e){
	e.parentElement.style.display="none";
	document.getElementById("canEdit").value="";
	var selectDom = iframeDocument.getElementById("postilWord"+CKEditorParams.endorseId);
	CKEditorParams.editorObject.insertHtml("<p>"+selectDom.innerText+"</P>");
	selectDom.remove();
	CKEditorParams.endorseId --;
	noSelectText()
}
			
//删除批注
function deletePostil(e){
	var number = getLastChar(e.parentElement.getAttribute("id"));
	var selectDom = iframeDocument.getElementById("postilWord"+number);
	selectDom.className = "";
	selectDom.setAttribute("id","");

}

//点击批注 显示对应的批注
function bodyClick(ev){
	var ev = ev || event;
	var target = ev.target || ev.srcElement;
	if(target.className == "odoc_postilWord"){
		if(target.className == ""){
			return;
		}
		showPostil(target)
	}else{
		hidePostil()
	}
}

//显示批注
function showPostil(target){
	hidePostil();
	var number = getLastChar(target.getAttribute("id"));
	var postilItem = document.getElementById("postilItem"+number);
	postilItem.style.display="block";
}

//隐藏批注
function hidePostil(id){
	if(id){
		document.getElementById(id).style.display="none";
	}else{
		var postilItemList = document.getElementsByClassName("postilItem");
		for(var i = 0;i<postilItemList.length;i++){
			postilItemList[i].style.display="none";
		}
	}
}

//批注文本背景颜色显隐
function showPostilWord(){
	if(!CKEditorParams.showPostil){
		changePostilShow();
	}else{
		//changePostilhide();
	}
}

//改变批注的状态为隐藏
function changePostilhide(){
	document.getElementsByClassName("showPostil")[0].innerText="显示批注"
	CKEditorParams.showPostil = false;
	var postilWordList = iframeDocument.getElementsByClassName("odoc_postilWord");
	for(var i=0 ;i<postilWordList.length;i++){
		postilWordList[i].className= "odoc_postilWord1";
		i--;
	}
	hidePostil();
}

//改变批注的状态为显示
function changePostilShow(){
	changePostilStatus();
	var postilWordList = iframeDocument.getElementsByClassName("odoc_postilWord1");
	for(var i=0 ;i<postilWordList.length;i++){
		postilWordList[i].className= "odoc_postilWord";
		i--;
	}
}

function changePostilStatus(){
	document.getElementsByClassName("showPostil")[0].innerText="不显示批注"
	CKEditorParams.showPostil = true;
}

//获取当前时间
function getDate(){
	var nowDate = new Date();
	var year = nowDate.getFullYear();
	var month = resetTime(nowDate.getMonth()+1);
	var date =  resetTime(nowDate.getDate());
	var hour =  resetTime(nowDate.getHours());
	var minute = resetTime(nowDate.getMinutes());
	var second = resetTime(nowDate.getSeconds());
	var nowTime = year+"-"+month+"-"+date+"T"+hour+":"+minute+":"+second+"Z";
	return nowTime;
}

//获取批注当前时间
function getPostilDate(){
	var nowDate = new Date();
	var year = nowDate.getFullYear();
	var month = resetTime(nowDate.getMonth()+1);
	var date =  resetTime(nowDate.getDate());
	var hour =  resetTime(nowDate.getHours());
	var minute = resetTime(nowDate.getMinutes());
	var second = resetTime(nowDate.getSeconds());
	var nowTime = year+"-"+month+"-"+date+"&nbsp;"+hour+":"+minute+":"+second;
	return nowTime;
}

function resetTime(time){
	if(time > 9){
		return time;
	}else{
		return "0"+time;
	}
}

function submit(){
	var bodyDom = iframeDocument.getElementsByTagName("body")[0];
	var spanTags = bodyDom.getElementsByTagName("span");
	for(var i in spanTags){
		if(spanTags[i].className == "" || spanTags[i].className == "odoc_hide"){
			spanTags[i].remove();
			i--;
		}
	}
	console.log(typeof CKEDITOR.instances["editor1"].getData())
	
	var pTagList = iframeDocument.getElementsByTagName("body")[0].getElementsByTagName("p")
	var divTag = document.createElement("div");
	
	
	for(let i = 0;i < pTagList.length; i++){
		var pTagItem = pTagList[i];
		for(let j=0;j<pTagItem.childNodes.length;j++){
			if(pTagItem.childNodes[j].nodeType == 3){
				var ftTag = document.createElement("ft");
				ftTag.appendChild(pTagItem.childNodes[j]);
				pTagList[i].appendChild(ftTag)
			}else{
				pTagList[i].appendChild(pTagItem.childNodes[i])
			}
		}
		
		divTag.appendChild(pTagList[i])
		i--;
	}
	console.log(divTag.innerHTML)
	ck.set(divTag.innerHTML)
}

function moveToLeft(){
	var sel = CKEditorParams.editorObject.getSelection();
	var element = sel.getStartElement();
	//	sel.selectElement(element); 选择当前
	var findString;
	if(CKEditorParams.selectDelete){
//		findString = CKEditorParams.selectText;
//		
//		CKEditorParams.tempStr1 = CKEditorParams.tempStr1.slice(0,parseInt(-CKEditorParams.selectText.length))
	}else{
		findString = getLastChar(CKEditorParams.tempStr1)
		CKEditorParams.tempStr1 = CKEditorParams.tempStr1.slice(0,-1)
	}
	
	var ranges = sel.getRanges();
//	var startIndex = element.getHtml().indexOf(findString);
	if(CKEditorParams.deleteContinueCount > 0){
		CKEditorParams.startIndex -= 1;
	}
	var startIndex = CKEditorParams.startIndex;
	if (startIndex > -1) {
    ranges[0].setStart(element.getFirst(), startIndex);
    ranges[0].setEnd(element.getFirst(), startIndex);
    sel.selectRanges([ranges[0]]);
	}
	
	CKEditorParams.selectDelete = false;
}


function deleteSequence(){
		var sel = CKEditorParams.editorObject.getSelection()
		var ranges = sel.getRanges()[0]
		var previousNode = CKEditorParams.editorObject.getSelection().getRanges()[0].getPreviousNode()
		
		if(previousNode.$.parentElement.className.indexOf("xuhao") >-1){
			sel.selectElement(previousNode)
			CKEditorParams[previousNode.$.parentElement.className]--;
		}
}

function preventKey(e,keyCode){
	var ctrlKey = e.ctrlKey || e.metaKey;
  if(ctrlKey && keyCode == 86) {// ctrl + v
     CKEDITOR.tools.callFunction(22,this);
  }  
  if(ctrlKey && keyCode == 85){// ctrl + U
  	 event.cancel();
  }
  if(ctrlKey && keyCode == 73){//ctrl + I
  	 event.cancel();
  }
  if(ctrlKey && keyCode == 79){//ctrl + O
  	 event.cancel();
  }
  if(ctrlKey && keyCode == 89){//ctrl + v
  	CKEDITOR.tools.callFunction(28,this);
  }
  if(ctrlKey && keyCode == 66){//ctrl + B
  	event.cancel();
  }
}

function getNodePtag(node){
	var pTag = node.parentNode;
	if(pTag.tagName !=="P"){
		getNodePtag(pTag);
	}else{
		return pTag;
	}
}

function insertReviseItem(text,type){
	var reviseContent = document.getElementsByClassName("revise-content")[0];
	var typeText=""
	var titleNumberDom = document.getElementsByClassName("title-number")[0];
	var div = document.createElement("div");
	div.setAttribute("class","revise-item")
	div.setAttribute("id","reviseItem"+CKEditorParams.reviseCount)
	if(type == "insert"){
		typeText="插入的内容";
	}else{
		typeText="删除的内容"
	}
	div.innerHTML = '<div class="revise-top"><span class="revise-item-name">'+CKEditorParams.author+'</span><span class="revise-item-type">'+typeText+'</span></div><div class="revise-bottom">'+text+'</div>';   
	reviseContent.appendChild(div);
	titleNumberDom.innerHTML = CKEditorParams.reviseCount+"处修订";
}

function addRevise(){
  	var dom= ""
	  if(CKEditorParams.reviseType == "insert" ){
	  	dom= iframeDocument.getElementById("insertTag"+CKEditorParams.insertId)
	  }else{
	  	dom= iframeDocument.getElementById("delItem"+CKEditorParams.deleteId)
	  }
		
		var reviseitem = document.getElementById("reviseItem"+CKEditorParams.reviseCount);
		if(reviseitem == null){
			dom && insertReviseItem(dom.innerText,CKEditorParams.reviseType)
		}else{
			try{
				var reviseInfoDom = reviseitem.getElementsByClassName("revise-bottom")[0];
				reviseInfoDom.innerText = dom.innerText;

			}catch(e){console.log(e)}
		}
}
var needAdd =false;
var createdElement = null;
var createdElementid = '';
function deleteOne(event){
	var lastChar = getLastChar(CKEditorParams.tempStr1);
	console.log('CKEditorParams.tempStr1',CKEditorParams.tempStr1);
	if(lastChar == "" && selectedElement.$.tagName == 'P'){
		event.cancel();
	}
	if(lastChar == ""){
		
		var selection = CKEditorParams.editorObject.getSelection().getStartElement();
		console.log('selection',selection);
		moveToPreviousElement(CKEditorParams.editorObject.getSelection().getStartElement());
		lastChar = getLastChar(CKEditorParams.editorObject.getSelection().getStartElement().getText());
	}
	
	CKEditorParams.tempStr1 = CKEditorParams.tempStr1.slice(0,-1);

	console.log("delete--------------------[" + lastChar + "]");
	insertDelChar(lastChar);

}
//移动到前一节点
function moveToPreviousElement(selectedElement){
	console.log('moveToPreviousElement');
	console.log('moveToPreviousElement',selectedElement);
	console.log('moveToPreviousElement',selectedElement.getPrevious());
	if(selectedElement.getPrevious() == null && selectedElement.$.tagName != 'P'){
		var haspre = false;
		if(selectedElement.getParent().getChildren().length>0){
			for(var i =0; i< selectedElement.getParent().getChildren().length;i++){
				var tempElement = selectedElement.getParent().getChild(i);
				console.log(tempElement == selectedElement);
			}
		}
		selectedElement = selectedElement.getParent();
	}
	if(selectedElement.getPrevious().getText() == ""){
		try{
			moveToPreviousElement(selectedElement.getPrevious());
		}catch(e){}
	}
		
	// 将光标移至最末
	var range = CKEditorParams.editorObject.createRange();
	
	range.moveToElementEditEnd(selectedElement.getPrevious());

	range.select();
	range.scrollIntoView();
	CKEditorParams.tempStr1 = selectedElement.getPrevious().getText();
	
}
function insertDelChar(delWords){

	
	needAdd = true;
	// createdElement = '<del id="deltest_' + CKEditorParams.deleteId + '">' + lastChar +  '</del>';
	// createdElementid = "deltest_" + CKEditorParams.deleteId ;

    createdElement = CKEDITOR.dom.element.createFromHtml( '<s id="del_' + CKEditorParams.deleteId + '"></s>' );
	if(delWords == ' '){
		createdElement.appendHtml('&nbsp;');
	}else{
		createdElement.appendText(delWords);
	}
	
		CKEditorParams.editorObject.insertElement( createdElement );
	
	focusEditor('del_' + CKEditorParams.deleteId);
}

function deleteSelected(event){


	insertDelChar(event.editor.getSelection().getSelectedText());

}

function insertText(){
	CKEditorParams.insertContinueCount += 1;
	CKEditorParams.insertId +=1;
	CKEditorParams.reviseCount += 1;
	CKEditorParams.reviseType = "insert"
	var html = "<span class='tempStr1'>"+CKEditorParams.tempStr1+"</span>" +"<u class='odoc_insertTag' id='insertTag"+CKEditorParams.insertId+"' xiudingren='"+CKEditorParams.author+"'xiudingshijian='"+getDate()+"'>&thinsp;</u><span class='tempStr'>"+CKEditorParams.tempStr2+"</span>";
	CKEditorParams.node.innerHTML = html;
	var element = new CKEDITOR.dom.element(iframeDocument.getElementById("insertTag"+CKEditorParams.insertId));
	var sel = new CKEDITOR.dom.selection(element)
	var ranges = CKEditorParams.editorObject.createRange();
  ranges.setStart(element.getFirst(), 1);
  ranges.setEnd(element.getFirst(), 1);
  sel.selectRanges([ranges]);
}

function showInfo(e){
	var eDom = e.target;
	var popoverDom = document.getElementsByClassName("popover")[0]
	if(e.target.nodeName == "INS" || e.target.nodeName == "DEL"){
		if(CKEditorParams.hoverDom == e.target.getAttribute("id")){
			return ;
		}else{
			CKEditorParams.hoverDom = e.target.getAttribute("id");
		}
		var positionX = e.x+20;
		var positionY = e.y+20;
		var type ="插入的内容";
		if(e.target.nodeName == "DEL"){
			type = "删除的内容";
		}
		
		var dateStr = getTagTime(eDom.getAttribute("xiudingshijian"))
		var author = eDom.getAttribute("xiudingren")
		var html ='<div class="popover-info"><span class="popover-author">'+author+'</span><span class="popover-time">'+dateStr+'</span><span class="popover-type">'+type+'</span></div><div class="popover-content">'+eDom.innerText+'</div>'
		popoverDom.innerHTML = html;
		popoverDom.style.display = "block";
		popoverDom.style.top = positionY+"px";
		popoverDom.style.left = positionX+"px";
	}else if(e.target.nodeName == "SPAN" && (e.target.getAttribute("class")=="odoc_postilWord" || e.target.parentNode.getAttribute("class")=="odoc_postilWord")){
		if(e.target.parentNode.getAttribute("class")=="odoc_postilWord"){
			eDom = e.target.parentNode;
		}	
		if(CKEditorParams.hoverDom ==  e.target.getAttribute("id")){
				return;
			}else{
				CKEditorParams.hoverDom = e.target.getAttribute("id");
			}
		var positionX = e.x+20;
		var positionY = e.y+20;
		var dateStr = getTagTime(eDom.getAttribute("pizhushijian"))
		var author = eDom.getAttribute("pizhuren")
		var html ='<div class="popover-info"><span class="popover-author">'+author+'</span><span class="popover-time">'+dateStr+'</span><span class="popover-type">批注的内容</span></div><div class="popover-content">'+dateStr+'</div>'
		popoverDom.innerHTML = html;
		popoverDom.style.display = "block";
		popoverDom.style.top = positionY+"px";
		popoverDom.style.left = positionX+"px";
	}else{
		popoverDom.style.display = "none";
		CKEditorParams.hoverDom="";
	}
}

//隐藏提示信息
function hideTip(){
	document.getElementsByClassName("ant-modal-content")[0].style.display = "none" 
}





/*------------------------------外部调用的方法-------------------------------*/

/*-------组件 ----------*/

//插入分页符
function pagebreak(){
	CKEditorParams.editorObject.execCommand( 'pagebreak' );
}
//插入时间
function insertTimestamp(){
	CKEditorParams.editorObject.execCommand( 'qianshuriqi' );
}
//Ctrl+Z
function undo(){
	CKEditorParams.editorObject.execCommand( 'undo' );
}
//Ctrl+Y
function redo(){
	CKEditorParams.editorObject.execCommand( 'redo' );
}
//Ctrl+X
function cut(){
	CKEditorParams.editorObject.execCommand( 'cut' );
}
//Ctrl+C
function copy(){
	CKEditorParams.editorObject.execCommand( 'copy' );
}
//Ctrl+V
function paste(){
	CKEditorParams.editorObject.execCommand( 'paste' );
}

/*-----格式----*/

//标题
function execdocTitle(){
	CKEditorParams.editorObject.execCommand( 'docTitle' );
}
//副标题
function execfubiaoti(){
	CKEditorParams.editorObject.execCommand( 'fubiaoti' );
}
//文号
function execodocNumber (){
	CKEditorParams.editorObject.execCommand( 'odocNumber' );
}
//主送
function execzhusong (){
	CKEditorParams.editorObject.execCommand( 'zhusong' );
}
//正文
function execzhengwen(){
	CKEditorParams.editorObject.execCommand( 'zhengwen' );
}
//署名
function execshuming(){
	CKEditorParams.editorObject.execCommand( 'shuming' );
}
//附注
function execfuzhu(){
	CKEditorParams.editorObject.execCommand( 'fuzhu' );
}

//附注
function execqianshuriqi(){
	CKEditorParams.editorObject.execCommand( 'qianshuriqi' );
}

//显示批注
function showPostilList(bool){
	var postil =  document.getElementsByClassName("postil")[0];
	if(!bool){
		postil.style.display="block";
	}else{
		postil.style.display="none";
	}
}

//显示修订
function showReviseList(bool){
	var revise =  document.getElementsByClassName("revise")[0];
	if(!bool){
		revise.style.display="block";
	}else{
		revise.style.display="none";
	}	
}

//导入word的时候获取修订内容
function getReviseItem(){
	var iframeBody = iframeDocument.getElementsByTagName("body")[0];
	var delList = iframeBody.getElementsByTagName("s")
	var insList = iframeBody.getElementsByTagName("u")
	var reviseContent = document.getElementsByClassName("revise-content")[0];
	reviseContent.innerHTML = ""
	reviseContent.reviseCount = 0;
	setReviseItem(delList,reviseContent,"删除的内容")
	setReviseItem(insList,reviseContent,"插入的内容")
	document.getElementsByClassName("title-number")[0].innerText=CKEditorParams.reviseCount+"处修订";
}

//导入文件时创建修订的内容
function setReviseItem(listArr,boxDom,type){
	for(var i=0; i< listArr.length ;i++){
		CKEditorParams.reviseCount += 1;
		var div = document.createElement("div");
		div.setAttribute("class","revise-item");
		div.setAttribute("id","reviseItem"+CKEditorParams.reviseCount);
		var dateStr = getTagTime(listArr[i].getAttribute("xiudingshijian"))
		var xiudingren = listArr[i].getAttribute("xiudingren");
		var html = '<div class="revise-top"><span class="revise-item-name">'+xiudingren+'</span><span class="revise-item-type">'+type+'</span></div><div class="postilTime">'+dateStr+'<div class="revise-bottom">'+listArr[i].innerText+'</div>';
		div.innerHTML = html;
		boxDom.appendChild(div);
	}

}

//鼠标移动到批注上 显示批注详情
function getPositlItem(){
	var postilList = iframeDocument.getElementsByClassName("odoc_postilWord");
	CKEditorParams.endorseId = 0;
	document.getElementById("postilBox").innerHTML = ""
	for(var i=0; i< postilList.length ;i++){
		CKEditorParams.endorseId ++;
		var div = document.createElement("div");
		div.setAttribute("class","postilItem");
		div.setAttribute("id","postilItem"+CKEditorParams.endorseId);		
		var dateStr = getTagTime(postilList[i].getAttribute("pizhushijian"))
		var pizhuren = postilList[i].getAttribute("pizhuren");
		var pizhuneirong = postilList[i].getAttribute("pizhuneirong")
		var insertHtmlString='<div class="headPortrait"><span class="odoc_author">'+pizhuren+'</span></div><div class="postilContent"><div class="postilTime">'+dateStr+'</div><div class="postilText">'+pizhuneirong+'</div></div>'	;
		div.innerHTML = insertHtmlString;
		document.getElementById("postilBox").appendChild(div)
	}
	document.getElementById("postilNumber").innerText=CKEditorParams.endorseId+"处修订";
}

function getTagTime(time){
	return time.replace("T","&nbsp;").replace("Z","");
}

//点击接受
function clickReceiveRevise(){
	console.log("clickReceiveRevise")
}
//点击接受并移到下一处
function receiveReviseAndMoveToNext(){
	jQuery("u").add(jQuery('s')).each(function(index,ele){
		receiveRevise(ele);
	})
	console.log("receiveReviseAndMoveToNext")
}
function receiveRevise(ele){
	if(ele.tagName == 'U'){
		ele.outterHTML = ele.text();
	}
}
//接受此修订
function receiveOneRevise(){
	console.log("receiveOneRevise")
}
//接受所有修订
function receiveAllRevise(){
	console.log("receiveAllRevise")
}

//点击拒绝
function clickRejectRevise(){
	console.log("clickReject")
}
//拒绝并移到下一处
function rejectReviseAndMoveToNext(){
	console.log("rejectReviseAndMoveToNext")
}
//拒绝此修订
function rejectOneRevise(){
	console.log("rejectOneRevise")
}
//接受所有修订
function rejectAllRevise(){
	console.log("rejectAllRevise")
}

//上一处
function findPrevious(){
	console.log("findPrevious")
}

//下一处
function findNext(){
	console.log("findNext")
}
//上一条
function findPreviousItem(){
	console.log("findPrevious")
}
//上一条
function findNextItem(){
	console.log("findNextItem")
}

function focusEditor(tempid)
{
	// 获取焦点
	CKEditorParams.editorObject.focus();

	// 将光标移至最末
	var range = CKEditorParams.editorObject.createRange();
	range.moveToElementEditStart(CKEditorParams.editorObject.document.getById(tempid));

	range.select();
	range.scrollIntoView();
}
function recountRevise(){

		iframeDocument = document.getElementsByClassName('cke_wysiwyg_frame')[0].contentDocument;
		iframeWindow = document.getElementsByClassName('cke_wysiwyg_frame')[0].contentWindow;
		var iframeBody = iframeDocument.getElementsByTagName("body")[0];
		if(bool){
			var delList = iframeBody.getElementsByTagName("u")
			var insList = iframeBody.getElementsByTagName("s")
			console.log(delList.length,insList.length)
			var reviseContent = document.getElementsByClassName("revise-content")[0];
			reviseContent.innerHTML = ""
			reviseContent.reviseCount = 0;
			for(var i=0; i< delList.length ;i++){
				CKEditorParams.reviseCount += 1;
				var div = document.createElement("div");
				div.setAttribute("class","revise-item")
				div.setAttribute("id","reviseItem"+CKEditorParams.reviseCount)
				var dateStr = delList[i].getAttribute("xiudingshijian");
				dateStr = dateStr.replace("T","&nbsp;").replace("Z","");

				var html = '<div class="revise-top"><span class="revise-item-name">'+CKEditorParams.author+'</span><span class="revise-item-type">删除的内容</span></div> <div class="postilTime">'+dateStr+'</div><div class="revise-bottom">'+delList[i].innerText+'</div>';
				div.innerHTML = html;
				reviseContent.appendChild(div);

			}

			for(var i=0; i< insList.length ;i++){
				CKEditorParams.reviseCount += 1;
				var div = document.createElement("div");
				div.setAttribute("class","revise-item");
				div.setAttribute("id","reviseItem"+CKEditorParams.reviseCount);

				var dateStr = insList[i].getAttribute("xiudingshijian");
				dateStr = dateStr.replace("T","&nbsp;").replace("Z","");

				var html = '<div class="revise-top"><span class="revise-item-name">'+CKEditorParams.author+'</span><span class="revise-item-type">插入的内容</span></div><div class="postilTime">'+dateStr+'<div class="revise-bottom">'+insList[i].innerText+'</div>';
				div.innerHTML = html;
				reviseContent.appendChild(div);
			}
			document.getElementsByClassName("title-number")[0].innerText=CKEditorParams.reviseCount+"处修订";
			
		}
}